{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Sorting a list with 3 unique numbers\n",
    "\n",
    "[The Original Question](https://mp.weixin.qq.com/s/2wHSwnSA6VwlkYWn98PcsA)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "Given a list of numbers with only 3 unique numbers (from `1` to `3`), sort the list in $O(n)$ time."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example\n",
    "\n",
    "```text\n",
    "Input: [3, 3, 2, 1, 3, 2, 1]\n",
    "Output: [1, 1, 2, 2, 3, 3, 3]\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Challenge\n",
    "\n",
    "Try sorting the list using constant space."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def challenge_sort(array: list):\n",
    "    pt = 0\n",
    "    while array[pt] == 1:\n",
    "        pt += 1\n",
    "    end = len(array) - 1\n",
    "    while array[end] == 3:\n",
    "        end -= 1\n",
    "    while pt < len(array):\n",
    "        if array[pt] == 1:\n",
    "            array = [array[pt], *array[:pt], *array[pt + 1:]]\n",
    "        elif array[pt] == 3 and pt < end:\n",
    "            array = [*array[:pt], *array[pt + 1:], array[pt]]\n",
    "            end -= 1\n",
    "        else:\n",
    "            pt += 1\n",
    "    return array"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 1, 2, 2, 3, 3, 3]\n"
     ]
    }
   ],
   "source": [
    "print(challenge_sort([3, 3, 2, 1, 3, 2, 1]))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
